package com.educate.common.filter;

import lombok.extern.log4j.Log4j2;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Log4j2
@Order(0)
public class FilterCrossDomain implements Filter {

    @Override
    public void init(FilterConfig arg0) {
        log.debug("------------FilterCrossDomain Init--------------");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest res = (HttpServletRequest) servletRequest;
        HttpServletResponse rep = (HttpServletResponse) servletResponse;
        rep.setHeader("Access-Control-Allow-Origin", res.getHeader("Origin"));//http://117.48.193.122:46000,\"+res.getHeader(\"Origin\")
        rep.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, content-type, Accept, token, timestamp");
        rep.setHeader("Access-Control-Allow-Methods", "*");
        rep.setHeader("Access-Control-Max-Age", "3600");
        rep.setHeader("Access-Control-Allow-Credentials", "true"); //是否支持cookie跨域
        if ("OPTIONS".equalsIgnoreCase(res.getMethod())) {
            return;
        }
        chain.doFilter(res, rep);
    }

    @Override
    public void destroy() {
        log.debug("Filter destroy");
    }
}